const WeChatPayServer = require('../server/weChat/weChatPayServer');
const WeChatPayDao = require('../dao/weChatPayDao');
const UserDao = require('../dao/userDao');
const Xml2js = require('xml2js');
const Crypto = require('crypto');

exports.createOrder = function (params) {
    return new Promise(function (resolve,reject) {
        let _result = {};
        let payParams = {};
        mysqlHelper.getConn()
            .then(function (conn) {
                conn.openTransaction()
                    .then(function () {
                        return WeChatPayDao.createOrder(conn,params);
                    })
                    .then(function () {
                        return WeChatPayServer.placeOrder(params);
                    })
                    .then(function (result) {
                        _result = result;
                        return WeChatPayDao.updateOrder(conn,{
                            RechargeTradeNo:params.RechargeTradeNo,
                            RechargePrepayId:result.xml.prepay_id
                        });
                    })
                    .then(function () {
                        payParams = {
                            appId:config.weChat.AppID,
                            timeStamp:new Date().getTime().toString().substr(0, 10),
                            nonceStr:getRandomString(),
                            package:"prepay_id="+_result.xml.prepay_id,
                            signType:"MD5"
                        };
                        payParams.paySign= getSignature(payParams);
                        console.log("=payParams=",payParams);
                    })
                    .then(function (result) {
                        return conn.commitTransaction();
                    }, function (err) {
                        conn.rollbackTransaction();
                        throw err;
                    })
                    .then(function () {
                        conn.releaseConn();
                        resolve(payParams);
                    }, function (err) {
                        console.log(err);
                        conn.releaseConn();
                        reject(err)
                    });
            });
    });
};
exports.rechargeNotify =function (params) {
    console.log("=rechargeNotify=",params);
    return new Promise(function (resolve,reject) {
        Xml2js.parseString(params,{explicitArray:false},function(err,result){
            console.log("=rechargeNotify result=",result);
            if(err){
                reject('<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[xml解析错误]]></return_msg></xml>');
            }else{
                if(result.xml.result_code == 'SUCCESS' && result.xml.return_code == 'SUCCESS'){
                    mysqlHelper.getConn()
                        .then(function (conn) {
                            conn.openTransaction()
                                .then(function () {
                                    return WeChatPayDao.updateOrder(conn,{
                                        RechargeTradeNo:result.xml.out_trade_no,
                                        RechargeStatus:'SUCCESS',
                                        RechargeTransactionId:result.xml.transaction_id
                                    });
                                })
                                .then(function () {
                                    return WeChatPayDao.queryOrder(conn,{RechargeTradeNo:result.xml.out_trade_no});
                                })
                                .then(function (result) {
                                    return UserDao.addPaidAddNum(conn,{
                                        PaidAddNum:result[0].AddTimes,
                                        openid:result[0].openid
                                    });
                                })
                                .then(function (result) {
                                    return conn.commitTransaction();
                                }, function (err) {
                                    conn.rollbackTransaction();
                                    throw err;
                                })
                        });
                }
                resolve('<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[SUCCESS]]></return_msg></xml>');
            }
        });
    });

};

function getSignature(params) {
    let keyArray = [];
    let signatureStr = "";
    delete params.sign;
    for (let key in params) {
        keyArray.push(key);
    }
    keyArray.sort();
    for (let i in keyArray) {
        if (params[keyArray[i]] != null) {
            signatureStr += keyArray[i] + "=" + params[keyArray[i]] + "&";
        }
    }
    signatureStr += "key=" + config.weChatPay.PaySecret;
    console.log("=signatureStr=",signatureStr);
    return Crypto.createHash("md5").update(signatureStr,'utf8').digest("hex").toUpperCase();
}
function getRandomString(){
    let chararray = ['1','2','3','4','5','6','7','8','9','0','Q','W','E','R','T','Y','U','I','O','P','L','K','J','H','G','F','D','S','A','Z','X','C','V','B','N','M'];
    let result = "";
    for (let i = 0,l = 32-result.length; i < l; i++) {
        let id = Math.ceil(Math.random() * 35);
        result += chararray[id];
    }
    return result;
}
